<template>
  <van-button size="small" type="primary" native-type="button" :disabled="disabled" @click.stop="getCode()">{{ text }}</van-button>
</template>

<script>
import { Toast } from "vant";
import api from "@/api";

export default {
  props: {
    mobile: {
      type: [Number, String],
    },
  },
  data() {
    return {
      conut: 60,
      disabled: false,
      text: "发送验证码",
    };
  },
  methods: {
    getCode() {
      if (this.disabled) return false;

      if (!this.mobile) {
        Toast({
          message: "请填写手机号!",
          position: "top",
          type: "fail",
        });
        return false;
      }

      this.disabled = true;

      const query = {
        mobile: this.mobile,
      };

      api
        .getVerifyCode(query)
        .then((res) => {
          this.setCodeText();
        })
        .catch((e) => {
          this.disabled = false;
          Toast({
            message: e,
            position: "top",
          });
          throw e;
        });
    },
    setCodeText() {
      let num = 60;
      const setIntervalFn = setInterval(() => {
        num = num - 1;
        this.text = `重新发送 | ${num}s`;

        if (num === 0) {
          clearInterval(setIntervalFn);
          this.text = "获取验证码";
          this.disabled = false;
        }
      }, 1000);
    },
  },
};
</script>

<style lang="scss" scoped></style>
